package academic.nantes.teamsync;

import java.util.ArrayList;

import academic.nantes.teamsync.DAO.AvailableProjet;
import academic.nantes.teamsync.DAO.TeamSyncProject;
import academic.nantes.teamsync.constants.Cst;
import academic.nantes.teamsync.constants.Utils;
import academic.nantes.teamsync.webservices.MajSuivi;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

public class Partager extends ListActivity {

	private int idArticle = 0;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		Intent thisIntent = getIntent();
		if (thisIntent.getExtras().containsKey("article"))
			idArticle = thisIntent.getExtras().getInt("article");

		setContentView(R.layout.vue_partage);

		majListe();

		Button btnPartager = (Button) findViewById(R.id.btnPartager);
		btnPartager.setOnClickListener(new OnClickListener() {
			public void onClick(View v) {
				partager();
			}
		});
	} 

	public void partager() {
		if (idArticle != 0) {
			String aPartager = "";
			ListView lv = getListView(); 
			SparseBooleanArray a = lv.getCheckedItemPositions();

			ArrayList<AvailableProjet> lv_items = TeamSyncProject.getInstance().getTousLesProjetsSaufCourant();

			for(int i = 0; i < lv_items.size() ; i++)
			{
				if (a.valueAt(i))
				{
					if (!aPartager.equals(""))
						aPartager += "-";
					aPartager += lv_items.get(i).getId();
					TeamSyncProject.getInstance().getSuivis().addSuivi(idArticle, lv_items.get(i).getId());
				}
				else
				{
					TeamSyncProject.getInstance().getSuivis().retirerSuivi(idArticle, lv_items.get(i).getId());
				}
			}


			Intent i = new Intent();
			i.putExtra("articleLu", idArticle);
			Log.d("params_sharing", "" + idArticle + ", " + aPartager);
			try{
				MajSuivi ws = new MajSuivi(idArticle, aPartager);
				ws.executeWebService();
				if(ws.getResultatWS().equals("OK")){
					setResult(Cst.reqstCode.Article.OK_PARTAGE,i);
				}
				else{
					setResult(Cst.reqstCode.Article.ERR_PARTAGE,i);
				}
			}catch(Exception e){
				Log.e("partage_WScall", e.toString());
				setResult(Cst.reqstCode.Article.ERR_PARTAGE,i);
			}
			finish();
		}
	}


	public boolean onKeyDown(int keyCode, KeyEvent event){

		Intent i = new Intent();
		i.putExtra("articleLu", idArticle);
		if (keyCode == KeyEvent.KEYCODE_BACK){
			setResult(Cst.reqstCode.General.BACK_BUTTON_PRESSED,i);
			finish();
		}
		return true;
	}


	private void majListe(){

		ArrayList<Integer> suiviPar = TeamSyncProject.getInstance().getSuivis().getProjets(idArticle);

		setListAdapter(new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_multiple_choice, TeamSyncProject.getInstance().getTousLesProjetsSaufCourantStringArray()));

		getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

		ArrayList<AvailableProjet> lv_items = TeamSyncProject.getInstance().getTousLesProjetsSaufCourant();
		String debugitems = "";
		for(int i = 0; i < lv_items.size(); i++){

			if (Utils.containsInt(suiviPar,lv_items.get(i).getId()))
			{
				getListView().setItemChecked(i, true);
			}
			else
			{
				getListView().setItemChecked(i, false);    				
			}
			debugitems += " " + lv_items.get(i).getId();
		}

		String debugsuivi = "article(" +idArticle+ ") suiviPar("+suiviPar.size()+") ";
		for (Integer proj:suiviPar){
			debugsuivi += " " + proj.toString(); 
		}
		Log.d("partager_majliste", "suivi " + debugsuivi + " \nitems " + debugitems);
		/*
        selectionner
		 */
		final ListView listView = getListView();

		listView.setItemsCanFocus(false);
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
		/*
		eAdapter = new EfficientAdapter(this, getIntent().getExtras().getInt("article"));

		ListView lv = getListView();
		setListAdapter(eAdapter);

		lv.setItemsCanFocus(false);

		lv.setTextFilterEnabled(true);
/*
		lv.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				onListItemClick(arg0, arg1, arg2, arg3);
			}

		});*/
	}

	/*
	public void showSelectedItems(){
		final SparseBooleanArray checkedItems = getListView().getCheckedItemPositions();
		if (checkedItems == null) {
			// That means our list is not able to handle selection
			// (choiceMode is CHOICE_MODE_NONE for example)
			return;
		}

		/*
		// For each element in the status array
		final int checkedItemsCount = checkedItems.size();
		for (int i = 0; i < checkedItemsCount; ++i) {
			// This tells us the item position we are looking at
			final int position = checkedItems.keyAt(i);

			// And this tells us the item status at the above position
			final boolean isChecked = checkedItems.valueAt(i);

			// And we can get our data from the adapter like that
			final Item currentItem = eAdapter.getItem(position);
		}* /
	}*/

	protected void onStop (){
		super.onStop();
		setListAdapter(null);
	}

	protected void onResume(){
		super.onResume();
		if (null == getListAdapter()){

			majListe();

		}
	}

	/*
	private static class EfficientAdapter extends BaseAdapter {
		private LayoutInflater mInflater;

		private ArrayList<Integer> suiviPar = new ArrayList<Integer>();

		public EfficientAdapter(Context context, int article) {
			// Cache the LayoutInflate to avoid asking for a new one each time.
			mInflater = LayoutInflater.from(context);
			suiviPar = TeamSyncProject.getInstance().getSuivis().getProjets(article);
		}

		/**
	 * The number of items in the list is determined by the number of speeches
	 * in our array.
	 *
	 * @see android.widget.ListAdapter#getCount()
		 /
		public int getCount() {
			return TeamSyncProject.getInstance().getTousLesProjets().size();
		}

		/**
	 * Since the data comes from an array, just returning the index is
	 * sufficent to get at the data. If we were using a more complex data
	 * structure, we would return whatever object represents one row in the
	 * list.
	 *
	 * @see android.widget.ListAdapter#getItem(int)
		 /
		public AvailableProjet getItem(int position) {
			return TeamSyncProject.getInstance().getTousLesProjets().get(position);
		}

		/**
	 * Use the array index as a unique id.
	 *
	 * @see android.widget.ListAdapter#getItemId(int)
		 /
		public long getItemId(int position) {
			return getItem(position).getId();
		}

		/**
	 * Make a view to hold each row.
	 *
	 * @see android.widget.ListAdapter#getView(int, android.view.View,
	 *      android.view.ViewGroup)
		 /
		public View getView(int position, View convertView, ViewGroup parent){ 
			ViewHolder holder;

			AvailableProjet item = (AvailableProjet)getItem(position); 
			convertView = mInflater.inflate(R.layout.listepartage_row, null); 

			convertView.setClickable(true);

			holder = new ViewHolder();
			holder.id = (TextView) convertView.findViewById(R.id.itemId);
			holder.name = (TextView)convertView.findViewById(R.id.itemName);
			holder.checkBox = (TextView) convertView.findViewById(R.id.itemCheckBox);
			holder.ligne = (LinearLayout)convertView.findViewById(R.id.itemLigneShare);

			convertView.setTag(holder);

			// Identifiant du projet

			holder.id.setText(Integer.toString(item.getId()));
			holder.id.setBackgroundColor(android.graphics.Color.TRANSPARENT);

			// Nom du projet
			holder.name.setText(item.getName());
			holder.name.setBackgroundColor(android.graphics.Color.TRANSPARENT);


			if(suiviPar.contains(item.getId()))
				holder.checkBox.setText('X'); 
			else 
				holder.checkBox.setText('O');
			holder.checkBox.setBackgroundColor(android.graphics.Color.TRANSPARENT);
			holder.checkBox.setFocusable(false);

			if (item.getId() == TeamSyncProject.getInstance().getIdProject()){
				holder.checkBox.setText('X');
			}
			if (null != AvailableProjetList.getInstance().getProjet(item.getId())){
				holder.ligne.setBackgroundColor(android.graphics.Color.argb(255, 220, 255, 248));
			}
			else{
				holder.ligne.setBackgroundColor(android.graphics.Color.DKGRAY);
			}
			return convertView; 
		} 

		static class ViewHolder {
			TextView id;
			TextView name;
			TextView checkBox;
			LinearLayout ligne;
		}
	}
	 */
}
